package com.wx.plugin.mp.core;

import com.wx.plugin.config.MPConfig;
import com.wx.plugin.constant.ValueConstant;
import com.wx.plugin.repository.*;
import com.wx.plugin.util.BusiUtil;
import com.wx.plugin.util.JSONUtil;
import com.yangzcp.userpojo.*;
import io.github.elkan1788.mpsdk4j.api.WechatAPI;
import io.github.elkan1788.mpsdk4j.common.EventType;
import io.github.elkan1788.mpsdk4j.core.WechatDefHandler;
import io.github.elkan1788.mpsdk4j.vo.event.BasicEvent;
import io.github.elkan1788.mpsdk4j.vo.event.ScanEvent;
import io.github.elkan1788.mpsdk4j.vo.message.Article;
import io.github.elkan1788.mpsdk4j.vo.message.BasicMsg;
import io.github.elkan1788.mpsdk4j.vo.message.NewsMsg;
import io.github.elkan1788.mpsdk4j.vo.message.TextMsg;
import lombok.extern.slf4j.Slf4j;
import org.nutz.lang.Strings;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * <p></p>
 *
 * @author  yangz
 * @date    2016/11/11
 * @version latest
 */
@Component
@Slf4j
public class WechatStandHandler extends WechatDefHandler{

    @Autowired
    private Keyword_repRepository keyword_repRepository;

    @Autowired
    private MPConfig mpConfig;

    @Autowired
    private WechatAPI wechatAPI;

    @Autowired
    private Members_yaoqingmaRepository members_yaoqingmaRepository;

    @Autowired
    private TransRepository transRepository;

    @Autowired
    private MembersRepository membersRepository;

    @Autowired
    private Members_account_log_onRepository members_account_log_onRepository;

    @Autowired
    private Members_accountRepository members_accountRepository;

    @Autowired
    private WXAPI wxapi;

    @Override
    public BasicMsg defEvent(BasicEvent be) {
        if(be instanceof PayEvent){
            try {
                PayEvent payEvent = (PayEvent) be;
                OrderRequestVO orderRequestVO = new OrderRequestVO();
                orderRequestVO.setOrder_id(payEvent.getOrderId());
                String order = wxapi.getOrder(orderRequestVO);
                OrderVOResult orderVOResult = JSONUtil.parse(order, OrderVOResult.class);
                OrderVO orderVO = orderVOResult.getOrder();
                Members member = membersRepository.findByWeixin_openid(orderVO.getBuyer_openid());
                if(member != null){
                    Trans trans = new Trans();
                    trans.setMoney(BusiUtil.convertMoney(orderVO.getOrder_total_price()));
                    trans.setOrder_no(orderVO.getOrder_id());
                    trans.setRef_member(member);
                    trans.setGoods_id(orderVO.getProduct_id());
                    trans.setGoods_name(orderVO.getProduct_name());
                    trans.setGoods_num(orderVO.getProduct_count());
                    trans.setOrder_flag(ValueConstant.DAI_FA_HUO);
                    if(member.getSale_id() == null){
                        trans.setOne_sale_id(null);
                        trans.setTow_sale_id(null);
                    }else{
                        Members sale = membersRepository.findOne(member.getSale_id());
                        if(ValueConstant.YES.equals(sale.getSale_flag())){
                            if(sale.getSale_level() == 1){
                                trans.setOne_sale_id(sale.getId());
                                trans.setTow_sale_id(member.getId());
                            }else if(sale.getSale_level() == 2){
                                trans.setOne_sale_id(sale.getRef_member().getId());
                                trans.setTow_sale_id(sale.getId());
                            }
                        }
//                        try {
//                            Members oneSale = membersRepository.findOne(trans.getOne_sale_id());
//                            Members twoSale = membersRepository.findOne(trans.getTow_sale_id());
//                            Members_account_log_on members_account_log_on = new Members_account_log_on();
//                            members_account_log_on.setAmount(trans.getMoney().multiply(member.getFenrun_rate()));
//                            members_account_log_on.setOrder_no(trans.getOrder_no());
//                            members_account_log_on.setRef_member(oneSale);
//                            members_account_log_on.setReson_type(ValueConstant.FEN_RUN);
//                            members_account_log_on.setReson(trans.getRef_member().getName() + " ：购买商品：" + trans.getGoods_name());
//                            members_account_log_on.setSale_flag(member.getSale_flag());
//                            members_account_log_on.setSale_level(member.getSale_level());
//                            members_account_log_on.setLog_level(1);
//                            members_account_log_onRepository.save(members_account_log_on);
//                            Members_account_log_on members_account_log_on2 = new Members_account_log_on();
//                            members_account_log_on2.setAmount(trans.getMoney().multiply(member.getFenrun_rate()));
//                            members_account_log_on2.setOrder_no(trans.getOrder_no());
//                            members_account_log_on2.setRef_member(twoSale);
//                            members_account_log_on2.setReson_type(ValueConstant.FEN_RUN);
//                            members_account_log_on2.setReson(trans.getRef_member().getName() + " ：购买商品：" + trans.getGoods_name());
//                            members_account_log_on2.setSale_flag(member.getSale_flag());
//                            members_account_log_on2.setSale_level(member.getSale_level());
//                            members_account_log_on2.setLog_level(2);
//                            members_account_log_onRepository.save(members_account_log_on2);
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                        }
                    }
                    transRepository.save(trans);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            TextMsg tm = new TextMsg(be);
            tm.setContent(Strings.join("\n", be.getEvent(), be.getEventKey()));
            return tm;
        }else {
            TextMsg tm = new TextMsg(be);
            tm.setContent(Strings.join("\n", be.getEvent(), be.getEventKey()));
            return tm;
        }
    }

    @Override
    public BasicMsg eSub(BasicEvent be) {
        if(EventType.subscribe.toString().equals(be.getEvent())){
            String openID = be.getFromUserName();
            String eventKey = be.getEventKey();
            Members members = membersRepository.findByWeixin_openid(openID);
            if(eventKey.startsWith("qrscene_")){
                Members_yaoqingma members_yaoqingma = new Members_yaoqingma();
                members_yaoqingma.setOpenid(openID);
                members_yaoqingma.setYaoqingma(eventKey.replace("qrscene_", ""));
                Members_yaoqingma byOpenid = members_yaoqingmaRepository.findByOpenid(openID);
                if(members == null){
                    if(byOpenid != null){
                        members_yaoqingmaRepository.delete(byOpenid.getId());
                    }
                    members_yaoqingmaRepository.save(members_yaoqingma);
                    TextMsg tm = new TextMsg(be);
                    tm.setContent("绑定成功, 您的上级是: " + members.getRef_member().getName());
                    return tm;
                }else{
                    TextMsg tm = new TextMsg(be);
                    tm.setContent("您已经扫过他的二维码: " + members.getRef_member().getName());
                    return tm;
                }
//                Follower follower = wechatAPI.getFollower(openID, "UTF-8");
//                Members byWeixin_openid = membersRepository.findByWeixin_openid(openID);
//                if(byWeixin_openid == null){
//                    Members members = new Members();
//                    members.setName(follower.getNickname());
//                    members.setWeixin_openid(follower.getOpenid());
//                    members.setCity(follower.getCity());
//                    members.setCountry(follower.getCountry());
//                    members.setProvince(follower.getProvince());
//                    members.setPhoto(follower.getHeadimgurl());
//                    members.setSex(BusiUtil.getSex(follower.getSex()));
//                    members.setYaoqing_ma(follower.getOpenid());
//                    members.setSubscribe_time(follower.getSubscribeTime());
//                    Members recommend = membersRepository.findByYaoqing_ma(members_yaoqingma.getYaoqingma());
//                    members.setLevel(recommend.getLevel() + 1);
//                    members.setRef_member(recommend);
//                    members.setRecommend_id2(recommend.getRef_member().getId());
//                    if(ValueConstant.YES.equals(recommend.getSale_flag())){
//                        members.setSale_id(recommend.getId());
//                    }else{
//                        members.setSale_id(recommend.getSale_id());
//                    }
//                    members.setSale_flag(ValueConstant.NO);
//                    membersRepository.save(members);
//                    Members_account members_account = new Members_account();
//                    members_account.setRef_member(members);
//                    members_account.setMoney(new BigDecimal(0));
//                    members_account.setGain_money(new BigDecimal(0));
//                    members_account.setSale_flag(ValueConstant.NO);
//                    members_account.setUpdate_time(new Date().getTime());
//                    members_account.setVersion(1);
//                    members_accountRepository.save(members_account);
//                }
            }
        }else if("merchant_order".equals(be.getEvent())){
        }
        TextMsg tm = new TextMsg(be);
        tm.setContent("欢迎关注-" + mpConfig.getNickname());
        return tm;
    }

    @Override
    public BasicMsg eScan(ScanEvent se) {
        TextMsg tm = new TextMsg(se);
        tm.setContent("欢迎回来-" + mpConfig.getNickname());
        return tm;
    }


    @Override
    public BasicMsg text(TextMsg tm) {
        try {
            Keyword_rep byKeyword = keyword_repRepository.findByKeyword(tm.getContent());
            if(byKeyword == null){
                TextMsg result = new TextMsg();
                BeanUtils.copyProperties(tm, result);
                List<Keyword_rep> keyword_repList = keyword_repRepository.findAll();
                StringBuilder sb = new StringBuilder();
                sb.append("可用关键字:");
                for (Keyword_rep keyword_rep : keyword_repList) {
                    sb.append(keyword_rep.getKeyword()).append(", ");
                }
                result.setContent(sb.toString());
                return result;
            }
            Integer rep_type = byKeyword.getRep_type();
            if(MPConstant.IMG_TEXT_MSG.equals(rep_type)){
                NewsMsg newsMsg = new NewsMsg();
                BeanUtils.copyProperties(tm, newsMsg);
                newsMsg.setMsgType("news");
                newsMsg.setCount(1);
                Article article = new Article();
                article.setDescription(byKeyword.getMark());
                article.setTitle(byKeyword.getTitle());
                article.setPicUrl(byKeyword.getPic_url());
                article.setUrl(byKeyword.getUrl());
                List<Article> articleList = new ArrayList<Article>();
                articleList.add(article);
                newsMsg.setArticles(articleList);
                return newsMsg;
            }else if(MPConstant.TEXT_MSG.equals(rep_type)){
                TextMsg result = new TextMsg();
                BeanUtils.copyProperties(tm, result);
                result.setContent(byKeyword.getContent());
                return result;
            }
            return tm;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return tm;
        }

    }

}
